package com.strongbj.iot.devices.newlight.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.newlight.message.NewLightReaderMessage;
import com.strongbj.iot.devices.newlight.response.common.HandleTimeStamp;

import io.netty.channel.ChannelHandlerContext;

/**
 * 0x08，标签盘点 
 * @author lei_w
 *
 */
public class InventoryResponseHandle implements IMessageHandle<NewLightReaderMessage, Object> {
	
	private static Logger logger = LogManager.getLogger(SingleInventoryResponseHandle.class.getName());
	
	@Override
	public boolean isHandle(NewLightReaderMessage t) {
		if (Integer.valueOf("8", 16).byteValue() == t.getType()) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightReaderMessage t) {
		String hostNumber = ByteUtil.byteArrToHexString(t.getAddress()); // reader 地址码
		String timeStamp = ByteUtil.byteArrToHexString(t.getTime()); // 时间戳
		
		short bindTagNum = ByteUtil.byteArrToShort(t.getBody(), 0); // 绑定的标签总数
		short newTagNum = ByteUtil.byteArrToShort(t.getBody(), 2); // 新加入的标签个数
		short lostTagNum = ByteUtil.byteArrToShort(t.getBody(), 4); //丢失的标签个数
		//String newTagAddress = ByteUtil.byteArrToHexString(t.getBody(), 6, 4); //新加入的标签IP
		String newTagAddress = ByteUtil.bytesToIp(ByteUtil.subBytes(t.getBody(), 6, 4)); // LED 标签地址
		String newTagShortAddress = ByteUtil.byteArrToHexString(t.getBody(), 10, 2); //新加入的标签段地址
		//String lostTagAddress = ByteUtil.byteArrToHexString(t.getBody(), 12, 4); //丢失的标签IP
		String lostTagAddress = ByteUtil.bytesToIp(ByteUtil.subBytes(t.getBody(), 12, 4)); //丢失的标签IP
		String time = ByteUtil.byteArrToHexString(t.getBody(), 16, 4); //最后全盘刷新时间戳
		String log = "\r\n===================================================" +
				"\r\n收到标签盘点返回报文：" +
				"\r\nREADER地址码：" + hostNumber + 
				"\r\n绑定的标签总数：" + bindTagNum +
				"\r\n新加入的标签个数：" + newTagNum +
				"\r\n丢失的标签个数：" + lostTagNum +
				"\r\n新加入的标签IP：" + newTagAddress + 
				"\r\n新加入的标签段地址：" + newTagShortAddress + 
				"\r\n丢失的标签IP：" + lostTagAddress + 
				"\r\n最后全盘刷新时间戳：" + HandleTimeStamp.handle(time) + 
				"\r\n时间戳：" + HandleTimeStamp.handle(timeStamp) + 
				"\r\n===================================================";
		logger.info(log);
		return null;
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}
}
